package com.example.pei.ithinklearnt.present;


import android.app.Activity;

import android.content.Context;
import android.content.Intent;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.net.Uri;
import android.os.Build;

import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;

import android.widget.Toast;


import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.UserInfo;

import com.example.pei.ithinklearnt.utils.ToastUtil;
import com.example.pei.ithinklearnt.view.interfaces.RegisterTwoInterface;

import java.io.File;
import java.io.FileNotFoundException;

import java.io.IOException;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

import static com.example.pei.ithinklearnt.utils.ActivityCollector.finishAll;
import static com.example.pei.ithinklearnt.utils.PermisionUtil.achieveAllPermisions;
import static com.example.pei.ithinklearnt.utils.PermisionUtil.checkWritePermission;

import static com.example.pei.ithinklearnt.utils.PhotoUtil.cropImageUri;
import static com.example.pei.ithinklearnt.utils.PhotoUtil.getPathFromAlbum;
import static com.example.pei.ithinklearnt.utils.PhotoUtil.updateUriFromFile;
import static com.example.pei.ithinklearnt.utils.PhotoUtil.updateUriFromPath;


public class RegisterTwoPresentImp implements RegisterTwoPresent {
    private RegisterTwoInterface registerTwoInterface;

    private final int ALL = 104;
    private final int onlyWrite=103;

    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 3;

    private Bitmap cropHeadBitmap;
    //头像在本地的存储路径
    private String headPath;

    private File headOutputCropImage;   //头像裁剪后的文件，即应当上传到服务器中的文件
    private Uri headimageCropUri;             //上面这个文件的URL，设置头像bitmap 用到的





    public RegisterTwoPresentImp(RegisterTwoInterface registerStepFourInterface){
        this.registerTwoInterface =registerStepFourInterface;
    }


    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    @Override
    public void chooseHeadFromCamera(int CAMERA_REQUEST_CODE) {
        //相机拍摄的临时文件
        File outputImage=new File(registerTwoInterface.getActivity().getExternalCacheDir(),"tmpCameraImage"+ registerTwoInterface.getPhoneNum()+".jpg");
        try {
            if(outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();
            headPath=outputImage.getPath();
        }catch (IOException e){
            e.printStackTrace();
        }

        Uri imageUri=updateUriFromFile(registerTwoInterface.getActivity(),outputImage);
        // 启动相机
        Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        registerTwoInterface.getActivity().startActivityForResult(intent,CAMERA_REQUEST_CODE);
    }

    @Override
    public void chooseHeadFromAlbum(int IMAGE_REQUEST_CODE) {
        //检查读写权限
        if(checkWritePermission(registerTwoInterface.getActivity(),onlyWrite)){
            openAlbum(IMAGE_REQUEST_CODE);   //拥有读写权限
        }
    }

    @Override
    public void openAlbum(int IMAGE_REQUEST_CODE) {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        registerTwoInterface.getActivity().startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }

    @Override
    public void achieveAllPermissions(Activity activity, int requestCode) {
        achieveAllPermisions(activity,requestCode);
    }


    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    @Override
    public void getPhotoAndCrop(Uri uri,int style,int requestCode) {
        Context context= registerTwoInterface.getActivity();
        headOutputCropImage=new File(context.getExternalCacheDir(), "head-" + registerTwoInterface.getUserName() + ".jpg");

        if(style==IMAGE_REQUEST_CODE){
            //如果是先从相册中选择的照片的路径
            headPath=getPathFromAlbum(context,uri);
        }else if(style==CAMERA_REQUEST_CODE){
            //如果是从相机拍照选择的
            //因为在启动相机的时候已经设置好了headPath的值，所以这里不需要再次设置
        }
        headimageCropUri=cropImageUri(registerTwoInterface.getActivity(),null,
                updateUriFromPath(context,headPath),headOutputCropImage,
                1,1,500,500, CROP_REQUEST_CODE);
    }

    @Override
    public void CropCallback(Intent data) {
        //显示裁剪后的图片
        if(headimageCropUri!=null){
            try {
                cropHeadBitmap=BitmapFactory.decodeStream(registerTwoInterface.getActivity().getContentResolver().openInputStream(headimageCropUri));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            registerTwoInterface.setHeadBitmap(cropHeadBitmap);        //设置view 中的头像
        }

    }



    @Override
    public void submit() {

        if(registerTwoInterface.getAim()==1){
            /**
             * 是用来修改的
             */
            if(registerTwoInterface.getHasChanged()){
                //如果头像修改了
                if(headimageCropUri!=null){
                    final BmobFile bmobFile = new BmobFile(headOutputCropImage);
                    bmobFile.uploadblock(new UploadFileListener() {
                        @Override
                        public void onProgress(Integer value) {}

                        @Override
                        public void done(BmobException e) {
                            final UserInfo newUser = new UserInfo();
                            final UserInfo current=AppApplication.getCurrentUser();
                            newUser.setHeadFileUrl(bmobFile.getFileUrl());
                            newUser.setNickName(registerTwoInterface.getUserName());
                            newUser.setBirthDay(registerTwoInterface.getBirthday());
                            if(registerTwoInterface.getSex()!=3) {  //3代表未选择（是注册时候用来判断有没有选中的
                                newUser.setSex(registerTwoInterface.getSex());
                                current.setSex(registerTwoInterface.getSex());
                            }
                            current.setHeadFileUrl(bmobFile.getFileUrl());
                            current.setNickName(registerTwoInterface.getUserName());
                            current.setBirthDay(registerTwoInterface.getBirthday());
                            newUser.update(current.getObjectId(),new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if(e==null){
                                        ToastUtil.ToastShow(registerTwoInterface.getActivity(),"修改成功! (￣▽￣)／",0);
                                        AppApplication.setCurrentUser(current);   //更新本地用户
                                        //会话：2.7、更新用户资料，用于在会话页面、聊天页面以及个人信息页面显示
                                        BmobIM.getInstance().
                                                updateUserInfo(new BmobIMUserInfo(current.getObjectId(),
                                                        current.getNickName(), current.getHeadFileUrl()));
                                        registerTwoInterface.getActivity().finish();
                                    }else{
                                        ToastUtil.ToastShow(registerTwoInterface.getActivity(),"修改失败...(╥╯^╰╥)",0);
                                    }
                                }
                            });
                        }
                    });
                }else{
                    final UserInfo current = AppApplication.getCurrentUser();
                    final UserInfo newUser = new UserInfo();
                    current.setNickName(registerTwoInterface.getUserName());
                    current.setBirthDay(registerTwoInterface.getBirthday());
                    newUser.setNickName(registerTwoInterface.getUserName());
                    newUser.setBirthDay(registerTwoInterface.getBirthday());
                    if(registerTwoInterface.getSex()!=3) {   //3代表未选择（是注册时候用来判断有没有选中的
                        newUser.setSex(registerTwoInterface.getSex());
                        current.setSex(registerTwoInterface.getSex());
                    }

                    newUser.update(current.getObjectId(),new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                ToastUtil.ToastShow(registerTwoInterface.getActivity(),"修改成功! (￣▽￣)／",0);
                                AppApplication.setCurrentUser(current);   //更新本地用户
                                //会话：2.7、更新用户资料，用于在会话页面、聊天页面以及个人信息页面显示
                                BmobIM.getInstance().
                                        updateUserInfo(new BmobIMUserInfo(current.getObjectId(),
                                                current.getNickName(), current.getHeadFileUrl()));
                                registerTwoInterface.getActivity().finish();
                            }else{
                                ToastUtil.ToastShow(registerTwoInterface.getActivity(),"修改失败...(╥╯^╰╥)",0);
                            }
                        }
                    });
                }
            }else{
                //没有修改任何东西 直接退出
                registerTwoInterface.getActivity().finish();
            }

        }else{
            /**
             * 是用来注册的
             */
            final Context context= registerTwoInterface.getActivity();
            if(headPath==null||cropHeadBitmap==null){
                Toast.makeText(context,"请设置头像",Toast.LENGTH_SHORT).show();
            }else if(registerTwoInterface.getSex()==3) {
                Toast.makeText(context,"请设置性别",Toast.LENGTH_SHORT).show();
            }else if(registerTwoInterface.getAge()==200) {
                Toast.makeText(context,"请设置年龄",Toast.LENGTH_SHORT).show();
            }else {
                registerTwoInterface.setprogressBarVisibility(true);//设置可见
                registerTwoInterface.setButtomSubmitClickable(false);//设置不可点击注册



                final BmobFile bmobFile = new BmobFile(headOutputCropImage);
                bmobFile.uploadblock(new UploadFileListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            final UserInfo userinfo = new UserInfo();
                            userinfo.setPassword(registerTwoInterface.getPassWord());
                            userinfo.setNickName(registerTwoInterface.getUserName());    //这是昵称 ，可以修改
                            userinfo.setUsername(registerTwoInterface.getUserName()+"_"+registerTwoInterface.getSex()); //用户名 不可修改
                            userinfo.setUserType(1);//设置为普通用户
                            userinfo.setHeadFileUrl(bmobFile.getFileUrl());
                            userinfo.setBirthDay(registerTwoInterface.getBirthday());
                            userinfo.setSex(registerTwoInterface.getSex());
                            userinfo.setMobilePhoneNumber(registerTwoInterface.getPhoneNum());
                            userinfo.setMobilePhoneNumberVerified(true);
                            userinfo.signUp(new SaveListener<UserInfo>() {
                                @Override
                                public void done(UserInfo userInfo, BmobException e) {
                                    if (e == null) {
                                        Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT).show();
                                        registerTwoInterface.setprogressBarVisibility(false);//设置bu可见
                                        AppApplication.setCurrentUser(userInfo);
                                        Intent intent=new Intent("main_Activity");
                                        Bundle bundle=new Bundle();
                                        bundle.putParcelable("currentUser", userinfo);
                                        intent.putExtras(bundle);
                                        registerTwoInterface.getActivity().startActivity(intent);

                                        finishAll();                //销毁所有与注册相关的活动
                                    } else {
                                        Toast.makeText(context, "注册失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                                        registerTwoInterface.setprogressBarVisibility(false);//设置不可见
                                        registerTwoInterface.setButtomSubmitClickable(true);//设置可点击注册

                                    }
                                }
                            });

                        } else {
                            Toast.makeText(context, "上传失败" + e.getMessage(), Toast.LENGTH_LONG).show();
                            registerTwoInterface.setprogressBarVisibility(false);//设置不可见
                            registerTwoInterface.setButtomSubmitClickable(true);//设置可点击注册
                        }
                    }

                    @Override
                    public void onProgress(Integer value) {
                        super.onProgress(value);
                    }
                });
            }
        }




    }


}
